package com.butterfly.rest.resource.restlet.server;


import com.butterfly.rest.resource.restlet.exception.AdXException;
import com.butterfly.rest.resource.restlet.misc.Constants;
import com.butterfly.rest.resource.restlet.status.AdxErrorCode;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Scope(value = "prototype")
public class ResourceParameterAccess {

    public ResourceParameterAccess() {

        System.out.println("RPA");
    }

    public long readUserId(Map<String, Object> requestAttributes) {
        try {
            return Long.parseLong(String.valueOf(requestAttributes.get(Constants.ACCOUNT_ID)));
        } catch (Exception e) {
            throw new AdXException(AdxErrorCode.INVALID_FORMAT_USER_ID);
        }
    }

    public int readPage(Map<String, Object> requestAttributes) {
        String page = (String) requestAttributes.get(Constants.PAGE);
        if (page != null) {
            try {
                int iPage = Integer.parseInt(page);
                if (iPage < 0) {
                    return 0;
                }
            } catch (Exception e) {
                throw new AdXException(AdxErrorCode.INVALID_PAGE_FORMAT);
            }
        }
        return 0;
    }

    public int readPageSize(Map<String, Object> requestAttributes) {
        String pageSize = (String) requestAttributes.get(Constants.PAGE_SIZE);
        if (pageSize != null) {
            try {
                int iPageSize = Integer.parseInt(pageSize);
                if (iPageSize > Constants.PAGE_SIZE_MAX) {
                    return Constants.PAGE_SIZE_MAX;
                }
                return iPageSize;
            } catch (Exception e) {
                throw new AdXException(AdxErrorCode.INVALID_PAGE_SIZE_FORMAT);
            }
        }
        return 0;
    }
}
